#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        vector<vector<int>> result;
        sort(nums.begin(), nums.end());
        int n = nums.size();
        int key = 0;
        while (key < n - 2)
        {
            int left = key + 1, right = n - 1;
            while (left < right)
            {
                if (nums[left] + nums[right] > (-nums[key]))
                    right--;
                else if (nums[left] + nums[right] < (-nums[key]))
                    left++;
                else
                {
                    result.push_back({ nums[key], nums[left], nums[right] });
                    if (nums[left] == nums[left + 1])
                        while (left < right && nums[left + 1] == nums[left])
                            left++;
                    if (nums[right] == nums[right - 1])
                        while (left < right && nums[right - 1] == nums[right])
                            right--;
                    left++;
                    right--;
                }
            }
            if (nums[key] == nums[key + 1] && key < n)
                while (key + 1 < n && nums[key] == nums[key + 1])
                    key++;
            key++;
        }
        return result;
    }
};